package com.stars.easyms.datasource.autoconfigure;

import com.stars.easyms.base.util.ClassUtil;
import com.stars.easyms.datasource.EasyMsMultiDataSource;
import com.stars.easyms.datasource.common.EasyMsDataSourceConstant;
import com.stars.easyms.datasource.compatibility.EasyMsJdbcPropertiesCompatibility;
import com.stars.easyms.datasource.jdbc.EasyMsJdbcTemplate;
import com.stars.easyms.datasource.jdbc.EasyMsNamedParameterJdbcTemplate;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;

import javax.sql.DataSource;

/**
 * <p>className: EasyMsJdbcTemplateAutoConfiguration</p>
 * <p>description: EasyMs的JdbcTemplate的自动配置类</p>
 *
 * @author guoguifang
 * @date 2019-11-22 19:07
 * @since 1.4.1
 */
@Configuration
@ConditionalOnClass({DataSource.class, JdbcTemplate.class})
@ConditionalOnSingleCandidate(DataSource.class)
@AutoConfigureAfter(EasyMsDatasourceAutoConfiguration.class)
public class EasyMsJdbcTemplateAutoConfiguration {

    @Configuration
    static class EasyMsJdbcTemplateConfiguration {

        private final EasyMsMultiDataSource easyMsMultiDataSource;

        EasyMsJdbcTemplateConfiguration(EasyMsMultiDataSource easyMsMultiDataSource) {
            this.easyMsMultiDataSource = easyMsMultiDataSource;
        }

        @Bean
        @Primary
        @ConditionalOnMissingBean(JdbcOperations.class)
        public EasyMsJdbcTemplate easyMsJdbcTemplate() {
            EasyMsJdbcTemplate easyMsJdbcTemplate = new EasyMsJdbcTemplate(this.easyMsMultiDataSource);
            // springboot1.x.x版本没有JdbcProperties类，因此需要做兼容
            if (ClassUtil.isExist(EasyMsDataSourceConstant.JUDGE_JDBC_PROPERTIES_IS_EXIST_CLASS)) {
                EasyMsJdbcPropertiesCompatibility.initEasyMsJdbcTemplate(easyMsJdbcTemplate);
            }
            return easyMsJdbcTemplate;
        }

    }

    @Configuration
    @Import(EasyMsJdbcTemplateConfiguration.class)
    static class EasyMsNamedParameterJdbcTemplateConfiguration {

        @Bean
        @Primary
        @ConditionalOnSingleCandidate(EasyMsJdbcTemplate.class)
        @ConditionalOnMissingBean(NamedParameterJdbcOperations.class)
        public EasyMsNamedParameterJdbcTemplate easyMsNamedParameterJdbcTemplate(EasyMsJdbcTemplate jdbcTemplate) {
            return new EasyMsNamedParameterJdbcTemplate(jdbcTemplate);
        }

    }

}